package com.common.www.controller.programme;

import com.alibaba.fastjson.JSON;
import org.springframework.boot.base.jpa.service.IBaseService;
import com.common.www.bean.entity.Result;
import com.common.www.bean.entity.programme.PrecipitateSsdb;
import com.common.www.controller.base.DefaultCrudController;
import com.common.www.data.NetCode;
import com.common.www.service.programme.PrecipitateSsdbService;
import com.common.www.service.project.ProjectService;
import com.common.www.service.project.BiddingCompanyService;
import com.common.www.utils.ParamsUtils;
import com.common.www.utils.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.*;


@CrossOrigin
@RestController
@RequestMapping(value = {"mgt/precipitateSsdb"})
@Api(tags = "MGT 高低压配电实施定标数据沉淀接口")
public class MGTPrecipitateSsdbController extends DefaultCrudController<PrecipitateSsdb, Long> {
    @Autowired
    private PrecipitateSsdbService service;
    @Autowired
    private ProjectService projectService;
    @Autowired
    private BiddingCompanyService biddingCompanyService;

    protected IBaseService getService() {
        return service;
    }



    @ApiOperation("编辑差异信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "json", value = "String", defaultValue = ""),
    })
    @RequestMapping(value = "/saveByJson", method = RequestMethod.POST)
    public Result saveByJson(String json) {
        PrecipitateSsdb contrast = JSON.parseObject(json, PrecipitateSsdb.class);
        if (contrast.getId() == null) {
            service.saveAndFlush(contrast);
        } else {
            // 如果 id 不为空，则从数据库中获取现有对象
            PrecipitateSsdb existingProject = service.getByIdLogic(contrast.getId());
            if (existingProject != null) {
                // 如果存在，则更新现有对象的属性
                BeanUtils.copyProperties(contrast, existingProject, "id");
                // 然后保存更新后的对象
                service.saveAndFlush(existingProject);
            } else {
                // 如果不存在，则保存解析出来的对象
                service.saveAndFlush(contrast);
            }
        }
        return R.ok(contrast);
    }


    @ApiOperation("批量删除启用")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "ids", value = "String", defaultValue = ""),
            @ApiImplicitParam(name = "operate", value = "1.删除 2.启用", defaultValue = ""),
    })
    @RequestMapping(value = "/batchDelete", method = RequestMethod.POST)
    public Result batchDelete(Long[] ids, Integer operate) {
        if (ParamsUtils.isInputEmpty(ids, operate)) {
            return R.returnCode(NetCode.CODE_INPUT_OMIT);
        }
        for (int i = 0; i < ids.length; i++) {
            PrecipitateSsdb contrast = service.findOne(ids[i]);
            if(contrast!=null){
                contrast.setFlag(0);
                service.save(contrast);
            }
        }
        return R.ok();
    }



    @ApiOperation(value = "查询供应商实施定标沉淀信息", nickname = "", notes = "")
    @ApiImplicitParams(value = {
    })
    @RequestMapping(value = "/getSsdbList", produces = {"application/json"}, method = RequestMethod.POST)
    public Result getSsdbList(Long projectId,Integer conditionType) {
        HashMap hashMap = new HashMap();
        hashMap.put("project.id", projectId);
        List<PrecipitateSsdb> ssdbList = service.getListLogic(hashMap, null);
        List<Map<String, Object>> mapList = service.getAssembleSsdbList(ssdbList,conditionType);
        return R.ok(mapList);
    }

    @ApiOperation("导出试试定标阶段数据沉淀")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "projectId", value = "String", defaultValue = ""),
    })
    @RequestMapping(value = "/exportSsdb", method = RequestMethod.GET)
    public Result exportSsdb(Long projectId) {
        HashMap hashMap = new HashMap();
        hashMap.put("project.id", projectId);
        List<PrecipitateSsdb> ssdbList = service.getListLogic(hashMap, null);
        List<Map<String, Object>> mapList = service.getAssembleSsdbList(ssdbList,1);
        //设置导出信息
        String fileName = ssdbList.get(0).getProject().getName();
        XSSFWorkbook workbook = service.exportSsdb(mapList);
        HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
        try {
            ServletOutputStream outputStream = response.getOutputStream();
            response.setContentType("application/binary;charset=UTF-8");
            response.setHeader("Content-Disposition", "attachment;fileName="
                    + URLEncoder.encode(fileName+"数据沉淀(实施定标)-导出.xlsx", "UTF-8"));
            response.setHeader("Pragma", "No-cache");
            workbook.write(outputStream);
            outputStream.flush();
            outputStream.close();
            response.flushBuffer();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (workbook != null) {
                    workbook.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return R.fail("导出错误");
    }



}

